import 'dart:async';
import 'package:get/get.dart';
import 'package:xinxuan/http/http_util_service.dart';
import 'package:xinxuan/vo/common_vo/common_pagination_vo.dart';
import 'package:xinxuan/vo/common_vo/common_times_vo.dart';
import 'package:xinxuan/vo/seckill_activity_products_vo.dart';

class SeckillPageController extends GetxController {

  int page = 1;
  /// 抢购商品列表
  var seckillListVo = SeckillActivityProductsVo(
    data: [],
    meta: SeckillActivityProductsMeta(
      times: CommonTimesVo(
        status: 0,
        surplus: 0,
        display: 0,
        explain: ''
      ),
      pagination: CommonPagination(
        total: 0
      )
    )
  ).obs;
  // /// 倒计时剩余时间
  var duration = 0.obs;
  /// 时间倒计时
  Timer? _timer;

  @override
  void onReady() {
    getSeckillList();
    super.onReady();
  }

  /// 获取抢购商品列表
  getSeckillList() async {
    page = 1;
    if (_timer != null) {
      _timer?.cancel();
    }
    // SeckillListVo tempVo = await HttpUtilService.getSeckillList(page: page);
    // seckillListVo.value = tempVo;
    SeckillActivityProductsVo tempVo = await HttpUtilService.getSeckillActivityProductsList(page: page);
    seckillListVo.value = tempVo;
    _calculationTime();
    update();
  }

  /// 加载更多抢购商品列表
  onloadSeckillList() async {
    if (seckillListVo.value.data!.length >= seckillListVo.value.meta!.pagination!.total!) {
      return;
    }
    page++;
    // SeckillListVo tempVo = await HttpUtilService.getSeckillList(page: page, loading: false);
    // seckillListVo.value.data!.addAll(tempVo.data!);
    SeckillActivityProductsVo tempVo = await HttpUtilService.getSeckillActivityProductsList(page: page, loading: false);
    seckillListVo.value.data!.addAll(tempVo.data!);
    seckillListVo.value.meta!.times = tempVo.meta!.times;
    seckillListVo.value.meta!.pagination = tempVo.meta!.pagination;
    update();
    _calculationTime();
  }

  /// 计算时间
  _calculationTime() {
    if (seckillListVo.value.meta!.times!.status == 2 || seckillListVo.value.meta!.times!.surplus! <= 0) {
      return;
    }
    duration.value = seckillListVo.value.meta!.times!.surplus!;
    _timer?.cancel();
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      duration.value--;
      print('duration.value: ${duration.value }');
      if (duration.value == 0) {
        _timer?.cancel();
        getSeckillList();
      }
    });
  }

  @override
  void onClose() {
    _timer?.cancel();
    super.onClose();
  }

}